let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//常量模块

//猜你喜欢
//思路：从整体数据中随机获取20条数据返回给客户端
function loveModel() {
    return async (req, res) => {
        let result = await loveData();//从数据库获取数据
        if (result.length > 0) {
            //从数据源完成随机获取20条数据
            let set = new Set();
            //循环，向set结构中添加20条随机商品数据
            while (set.size < 20) {
                let item = result[Math.floor(Math.random() * result.length)];//随机获取一条数据
                set.add(item);
            }
            let arr = [...set];//将set类型转换为数组类型
            SUCCESS(res, arr);
        } else {
            ERROR(res, '猜你喜欢查询失败', result)
        }
    };
}

//从数据库获取商品数据
async function loveData() {
    let [err, data] = await to(db.query(`SELECT goods_id,goods_name,goods_price,CONCAT(?,image_url) 
    as image_url FROM goods_list `, [HOST]));
    return err ? err : data;
}

module.exports = loveModel;